<template>
  <div>
    <el-card class="box-card" shadow="hover">
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="5">
          <div class="block">
            <span class="demonstration"></span>
            <el-cascader
              v-model="productType"
              :options="options"
              @change="handleChange"
              placeholder="商品分类"
            ></el-cascader>
          </div>
        </el-col>
        <el-col :span="4">
          <el-input v-model="search.keyword" placeholder="关键字" style="width: 80%;"></el-input>
        </el-col>
        <el-col :span="7" style="color: gray;">
          发布日期
          <el-date-picker
            v-model="releaseDate"
            type="daterange"
            style="width:60%;"
            :default-time="['12:00:00']"
            value-format="yyyy-MM-dd"
            @change="optTimeHandle"
          ></el-date-picker>
        </el-col>
        <el-col :span="5">
          <el-input v-model="search.lowPrice" placeholder="最低价格" style="width:40%;"></el-input>~
          <el-input v-model="search.highPrice" placeholder="最高价格" style="width: 40%;"></el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-row>
      <el-col :span="24">
        <el-menu class="el-menu-demo" mode="horizontal" @select="handleSelect">
          <el-menu-item index>全部</el-menu-item>
          <el-menu-item index="2">在售中</el-menu-item>
          <el-menu-item index="1">已售罄</el-menu-item>
        </el-menu>
      </el-col>
    </el-row>
    <el-row style="margin-top: 10px;">
      <el-col :span="24" style="margin-bottom: 10px;">
        <el-button type="primary" @click="addProduct">添加商品</el-button>
        <el-button @click="shangjia">上架</el-button>
        <el-button @click="xiaJia">下架</el-button>
        <el-button @click="updateType">修改分类</el-button>
        <el-button @click="deletePro">删除</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="商品编码"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="productImg" label="商品封面" width="180">
            <template slot-scope="scope">
              <img
                v-if="scope.row.productImg"
                :src="scope.row.productImg"
                style="width: 120px; height: 120px"
              />
            </template>
          </el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="cumulativeSales" label="销量"></el-table-column>
      <el-table-column prop="typeName" label="分类"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">{{showStatus(scope.row.status)}}</template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
            <span style="color: blue;cursor: pointer;" @click="bianJi(scope.row)">编辑</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row>
      <el-col :span="7" :offset="15">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[2, 4, 5, 8, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @next-click="nextPage"
            @prev-click="prevPage"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
    <!-- 嵌套表单 -->
    <el-dialog title="修改商品分类" :visible.sync="dialogFormVisible">
      <el-form>
        <el-form-item label="选择类别">
          <el-cascader :options="options" @change="updatePT" placeholder="商品分类"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="xiuGaiFenLei">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加商品 -->
    <el-dialog title="添加商品" :visible.sync="tjsp" style="width: 100%;">
      <el-form>
        商品封面
        <span style="color: red;">*</span>
        &nbsp;
        <el-form-item>
          <el-upload
            class="avatar-uploader"
            action="api/product-server/uploadimg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
          >
            <img v-if="form.imgSrc" :src="form.imgSrc" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div>仅支持jpg/png格式,大小不能超过2MB!</div>
        </el-form-item>商品详情图片
        <span style="color: red;">*</span>
        &nbsp;
        <el-form-item>
          <el-upload
            class="upload-demo"
            action="api/product-server/uploadimg"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleImgListSuccess"
            :show-file-list="true"
            :file-list="form.imgList"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
            list-type="picture"
            style="width: 20%"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <br />
          <div>仅支持jpg/png格式,大小不能超过2MB!</div>
        </el-form-item>
        <el-form-item>
          商品名称
          <span style="color: red;">*</span>&nbsp;
          <el-input v-model="form.name" placeholder="商品名称" style="width: 28%;"></el-input>
        </el-form-item>
        <el-form-item>
          商品价格
          <span style="color: red;">*</span> &nbsp;
          <el-input v-model="form.price" placeholder="商品价格" style="width: 28%;"></el-input>
        </el-form-item>
        <el-form-item>
          商品类别
          <span style="color: red;">*</span>
          &nbsp;
          <el-cascader :options="options" @change="AddPT" placeholder="商品分类"></el-cascader>
        </el-form-item>
        <el-form-item>
          商品状态
          <span style="color: red;">*</span>
          &nbsp;
          <el-select v-model="form.status">
            <el-option
              v-for="item in statusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          商品归属
          <span style="color: red;">*</span>
          &nbsp;
          <el-select v-model="form.ecss">
            <el-option v-for="item in ecssList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          库存量
          <span style="color: red;">*</span>
          &nbsp;
          &nbsp;
          <el-input v-model="form.stock" placeholder="库存量" style="width: 28%;"></el-input>
        </el-form-item>
        <el-form-item>
          业务类型
          <span style="color: red;">*</span>
          &nbsp;
          <el-select v-model="form.businessId">
            <el-option
              v-for="item in businessList"
              :key="item.id"
              :label="item.businessName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="consoleADD">取 消</el-button>
        <el-button type="primary" @click="queDinAdd">确 定</el-button>
      </div>
    </el-dialog>
    <el-drawer
      title="商品详情"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
      :size="'40%'"
      style="margin-top: 90px;height:90%"
    >
      <el-card class="box-card">
        <div style="text-align: center;">
        <template>
          <el-carousel height="500px">
            <el-carousel-item v-for="item in productDetail.imgList" :key="item.id">
              <img :src="item.imgSrc" style="width: 100%;height: 100%;"/>
            </el-carousel-item>
          </el-carousel>
        </template>
        商品名称：
        <el-input v-model="productDetail.name" style="width: auto;margin-top: 10px"></el-input>
        商品价格：
        <el-input v-model="productDetail.price" style="width: auto;margin-top: 10px"></el-input>
        商品销量：
        <el-input v-model="productDetail.cumulativeSales" style="width: auto;margin-top: 10px"></el-input>
        商品分类：
        <el-input v-model="productDetail.typeName" style="width: auto;margin-top: 10px"></el-input>
        商品状态：
        <el-input v-model="productDetail.status" style="width: auto;margin-top: 10px"></el-input>
        创建时间：
        <el-input v-model="productDetail.createTime" style="width: auto;margin-top: 10px"></el-input>
      </div>
      </el-card>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      productDetail:{
        BJImagSrc:"",
        name:"",
        price:"",
        imgList:[],
        cumulativeSales:"",
      },
      drawer: false,
      direction: "rtl",
      businessList: [],
      headers: {
        token: localStorage.getItem("token")
      },
      ecssList: [
        { id: 1, name: "中移" },
        { id: 0, name: "ECSS" }
      ],
      statusList: [
        { id: 1, name: "下架" },
        { id: 2, name: "上架" }
      ],
      form: {
        imgSrc: "",
        imgList: [],
        productType: ""
      },
      tjsp: false,
      updateproductId: "",
      dialogFormVisible: false,
      pageNum: 1,
      pageSize: 5,
      total: null,
      productType: [],
      options: [],
      releaseDate: [],
      productId: [],
      search: {
        keyword: "",
        lowPrice: "",
        highPrice: "",
        releaseDateStart: "",
        releaseDateEnd: "",
        typeId: "",
        parentId: "",
        status: ""
      },
      activeTab: "all",
      tableData: [],
      previewVisible: false, // 图片预览窗口开关
      previewPath: "" // 要预览的图片路径
    };
  },
  methods: {
    deletePro(){
      if (this.productId.length == 0) {
        this.$message.error("请选择商品!");
        return;
      }
      this.$axios.post("api/product-server/deleteProduct", this.productId).then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.handleSearch();
        }
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    bianJi(val) {
      console.log(val);
      this.drawer = true;
      let id = val.id;
      this.$axios.get('api/product-server/queryImgList',{params:{id:id}}).then(res=>{
        if(res.data.code==200){
          this.productDetail.imgList = res.data.data;
        }
      })
      this.productDetail.BJImagSrc = val.productImg;
      this.productDetail.name = val.name;
      this.productDetail.price = val.price;
      this.productDetail.cumulativeSales = val.cumulativeSales;
      this.productDetail.typeName = val.typeName;
      this.productDetail.status = val.status;
      this.productDetail.createTime = val.createTime;
    },
    consoleADD() {
      this.tjsp = false;
      this.options = [];
    },
    /**
     * 批量上传图片<br>
     * 图片上传成功回调函数<br>
     * 图片上传成功后触发
     * @param response 从后端直接获取的统一响应类，包括code、data、msg，其中data是返回给前端的图片utl
     * @param file 最新上传的图片对象信息，包含name、status、uid、url、response
     * @param fileList 目前上传到服务器的所有图片对象的数组，包含name、status、uid、url
     */
    handleImgListSuccess(response, file, fileList) {
      console.log(response.data);
      if (response.code === 200) {
        this.form.imgList.push(response.data);
      }
    },
    /**
     * 批量上传图片
     * 图片预览回调函数
     * @param file 预览的图片信息，包含name、status、uid、url四个属性
     */
    handlePreview(file) {
      this.previewVisible = true;
      this.previewPath = file.url;
    },
    /**
     * 批量上传图片<br>
     * 删除图片回调函数
     * @param file 已删除的图片信息，包含name、status、uid、url四个属性
     * @param fileList 目前还未删除的图片信息对象的数组，每个对象包含name、status、uid、url四个属性
     */
    handleRemove(file, fileList) {
      this.form.imgList = [];
      fileList.forEach(file => {
        const img = {
          name: file.name,
          url: file.url
        };
        this.form.imgList.push(img);
        this.$message.success("图片删除成功！");
      });
    },
    /**
     * 上传单个图片成功时触发的回显方法
     * @param res
     */
    handleAvatarSuccess(res) {
      console.log(res);
      if (res.code == 200) {
        this.form.imgSrc = res.data;
      }
    },
    // 对图片上传之前做校验，格式，大小，像素
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG || (isPNG && isLt2M);
    },
    AddPT(val) {
      this.form.productType = val[1];
    },
    queDinAdd() {
      this.$axios.post("api/product-server/addProduct", this.form).then(res => {
        if (res.data.code == 200) {
          this.$message.success("添加成功！");
          this.tjsp = false;
          this.handleSearch();
        }
      });
    },
    addProduct() {
      this.tjsp = true;
      this.form = {
        imgSrc: "",
        imgList: [],
        productType: ""
      };
      this.$axios.get("api/order-server/selectBusinessList").then(res => {
        if (res.data.code == 200) {
          console.log(res.data);
          this.businessList = res.data.data;
        }
      });
    },
    xiuGaiFenLei() {
      let XGFL = {
        productId: this.productId,
        typeId: this.updateproductId
      };
      this.$axios
        .post("api/product-server/updateProductType", XGFL)
        .then(res => {
          if (res.data.code == 200) {
            this.$message.success("修改成功！");
            this.dialogFormVisible = false;
            this.options = [];
            this.handleSearch();
          }
        });
    },
    updatePT(val) {
      this.updateproductId = val[1];
    },
    updateType() {
      if (this.productId.length == 0) {
        this.$message.error("请选择商品!");
        return;
      } else {
        this.options = [];
        this.selProductSort();
        this.dialogFormVisible = true;
      }
    },
    showStatus(val) {
      switch (val) {
        case 2:
          return "在售中";
        case 3:
          return "已售罄";
        case 1:
          return "已下架";
      }
    },
    shangjia() {
      if (this.productId.length == 0) {
        this.$message.error("请选择商品!");
        return;
      }
      this.$axios
        .post("api/product-server/shangJia", this.productId)
        .then(res => {
          if (res.data.code == 200) {
            this.$message.success("上架成功！");
            this.handleSearch();
          }
        });
    },
    xiaJia() {
      if (this.productId.length == 0) {
        this.$message.error("请选择商品!");
        return;
      }
      this.$axios
        .post("api/product-server/xiaJia", this.productId)
        .then(res => {
          if (res.data.code == 200) {
            this.$message.success("下架成功！");
            this.handleSearch();
          }
        });
    },
    handleSelectionChange(val) {
      this.productId = [];
      val.forEach(item => {
        this.productId.push(item.id);
      });
    },
    handleSelect(key, keyPath) {
      this.search.status = key;
      this.handleSearch();
    },
    handleReset() {
      this.search = {};
      this.options = [];
      this.releaseDate = [];
    },
    handleSearch() {
      let params = {};
      params.param = this.search;
      params.pageNum = this.pageNum;
      params.pageSize = this.pageSize;
      this.$axios
        .post("api/product-server/queryAllProduct", params)
        .then(res => {
          console.log(res.data);
          if (res.data.code == 200) {
            this.tableData = res.data.data.list;
            this.pageNum = res.data.data.pageNum;
            this.pageSize = res.data.data.pageSize;
            this.total = res.data.data.total;
          }
        });
    },
    prevPage(val) {
      this.pageNum = val;
      this.handleSearch();
    },
    nextPage(val) {
      this.pageNum = val;
      this.handleSearch();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.handleSearch();
    },

    //商品类型条件筛选
    handleChange(val) {
      this.search.typeId = val[1];
      this.search.parentId = val[0];
      this.handleSearch();
    },
    optTimeHandle() {
      this.search.releaseDateStart = this.releaseDate[0];
      this.search.releaseDateEnd = this.releaseDate[1];
    },
    selProductSort() {
      this.$axios.get("api/product-server/queryProductType").then(response => {
        if (response.data.code == 200) {
          let result = this.convertDataToOptions(response.data.data);
          this.options = result;
        }
      });
    },
    convertDataToOptions(data) {
      const topLevelOptions = {};
      const allOptions = {};

      data.forEach(item => {
        const option = {
          value: item.id,
          label: item.typeName
        };

        // 如果是顶级菜单，直接添加到顶层选项
        if (item.parentId === "-1") {
          topLevelOptions[item.id] = option;
        }

        // 存储所有选项，包括非顶级选项
        allOptions[item.id] = option;

        // 如果不是顶级菜单，找到父级并添加到其 children 中
        if (allOptions[item.parentId]) {
          if (!allOptions[item.parentId].children) {
            allOptions[item.parentId].children = [];
          }
          allOptions[item.parentId].children.push(option);
        }
      });

      // 将顶层选项转换为数组
      const result = Object.values(topLevelOptions);

      // 删除没有子元素的空 children 数组
      result.forEach(option => {
        if (option.children && option.children.length === 0) {
          delete option.children;
        }
      });

      return result;
    }
  },
  created() {
    this.selProductSort();
    this.handleSearch();
  },
  mounted() {
    window.vue = this;
  }
};
</script>

<style scoped>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #000000;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.box-card {
    width: 95%;
    height: 100%;
    margin: 0 auto;
}
</style>